﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VirtualBank.Data;
using VirtualBank.Data.Entities;
using WebLibrary;

namespace WebRoot
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (VirtualBankDataContext db = new VirtualBankDataContext())
                {
                    var bills = from b in db.Bills
                                where b.Frequency > 0
                                select b;
                    
                    BillSummary.DataSource = bills;
                    BillSummary.DataBind();
                }
            }
        }

        protected void BillSummary_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            Bill dataItem = (Bill)e.Item.DataItem;

            (e.Item.FindControl("Payee") as Literal).Text = dataItem.Account.Description;
            (e.Item.FindControl("AmountDue") as Literal).Text = String.Format("{0:C}", dataItem.AmountDue);
            (e.Item.FindControl("PayButton") as ImageButton).CommandArgument = dataItem.ID.ToString();

            VirtualBankDataContext db = new VirtualBankDataContext();

            if (dataItem.Account.OpeningBalance == null)
                (e.Item.FindControl("Balance") as Literal).Text = "N/A";
            else
            {
                var payments = from p in dataItem.Account.CreditTransactions
                               select p;

                decimal balance = (decimal)dataItem.Account.OpeningBalance.Value;
                if (payments != null)
                {
                    decimal totalPaid = payments.Sum(p => p.GrossAmount);
                    balance -= totalPaid;
                }

                (e.Item.FindControl("Balance") as Literal).Text = String.Format("{0:C}", balance);
            }

            DateTime? lastPayment = (from p in dataItem.Account.CreditTransactions
                                     orderby p.PaymentDate descending
                                     select p.PaymentDate).Take(1).SingleOrDefault();

            if (lastPayment == null)
                (e.Item.FindControl("LastPayment") as Literal).Text = "None";
            else
                (e.Item.FindControl("LastPayment") as Literal).Text = lastPayment.Value.ToShortDateString();

            (e.Item.FindControl("NextPayment") as Literal).Text = dataItem.DueDate.ToShortDateString();
        }

        protected void BillSummary_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            SavePayment.CommandArgument = (string)e.CommandArgument;

            var paymentAccounts = from p in Master.DataContext.Accounts
                                  select p;

            PaymentAccount.DataSource = paymentAccounts;
            PaymentAccount.DataTextField = "Description";
            PaymentAccount.DataValueField = "ID";
            PaymentAccount.DataBind();

            PaymentTo.Text = (e.Item.FindControl("Payee") as Literal).Text;
            AmountPaid.Text = (e.Item.FindControl("AmountDue") as Literal).Text;
            PaymentDate.Text = (e.Item.FindControl("NextPayment") as Literal).Text;

            ApplyPayment_PopupExtender.Show();
        }

        protected void SavePayment_Click(object sender, EventArgs e)
        {
            Transaction txn = new Transaction();
            txn.ConfirmationNumber = ConfirmationNumber.Text;
            txn.CreateDate = DateTime.Now;
            txn.TargetAccountID = int.Parse((sender as Button).CommandArgument);
            txn.SourceAccountID = int.Parse(PaymentAccount.SelectedValue);
            txn.GrossAmount = decimal.Parse(AmountPaid.Text);
            txn.PaymentDate = DateTime.Parse(PaymentDate.Text);
            txn.TransactionType = (byte)TransactionTypes.ManualPayment;
            txn.User = (User)Session["UserObject"];
            
            Master.DataContext.Transactions.InsertOnSubmit(txn);
            Master.DataContext.SubmitChanges();
        }
    }
}
